﻿using System;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

public class CreatLuaConfigUtil
{

    public static void CreatLuaConfigFile(UnityEngine.Object selectObj, string writePath)
    {
        string fileName = selectObj.name;
        string className = fileName;
        StreamWriter sw = new StreamWriter(Application.dataPath + writePath + className + ".lua");

        sw.WriteLine("local datatabel = require(\"DataTabel\")");
        sw.WriteLine("module(\"DataTabel."+ className + "\") ");
        sw.WriteLine("local " + className + " = {}");

        string filePath = AssetDatabase.GetAssetPath(selectObj);
        CsvStreamReader csr = new CsvStreamReader(filePath, Encoding.UTF8);
        string titles = className + "[\"titels\"] = {";
        string types = className + "[\"types\"] = {";
        string[] content = new string[csr.RowCount - 2]; 
        for (int colNum = 1; colNum < csr.ColCount + 1; colNum++)
        {
            string fieldName = csr[1, colNum];
            string fieldType = csr[2, colNum];
            if (colNum < csr.ColCount)
            {
                titles += "[\"" + csr[1, colNum] + "\"] = " + colNum + ",";
                types += "[\"" + csr[2, colNum] + "\"] = " + colNum + ",";
            }
            else
            {
                titles += "[\"" + csr[1, colNum] + "\"] = " + colNum + "}";
                types += "[\"" + csr[2, colNum] + "\"] = " + colNum + "}";
            }
            for (int i = 3; i < csr.RowCount + 1; i++)
            {
                content[i - 3] += Analysis_Type(csr[2, colNum], csr[i, colNum]);
            }
        }
        sw.WriteLine(titles);
        sw.WriteLine(types);
        sw.WriteLine(className + "[\"data\"] = ");
        sw.WriteLine("{");
        for (int j = 0; j < content.Length; j++)
        {
            sw.WriteLine("\t" + "{" + content[j] + "},");
        }
        //		filePath=filePath.Replace("Assets/Resources/","");
        //		filePath=filePath.Substring(0,filePath.LastIndexOf('.'));
        sw.WriteLine("}");
        sw.WriteLine("datatabel.DTMgr[\"TableSet\"][\"DataTable." + className + "\"] = " + className);

        sw.Flush();
        sw.Close();
        AssetDatabase.Refresh();        //这里是一个点

        
    }

    static string Analysis_Type(string type, string value)
    {
        switch (type)
        {
            case "Int":
                return value + ",";
            case "String":
                return "\"" + value + "\",";
            case "Boolean":
                return value + ",";
            default:
                return "无法识别";
        }
    }
}
